# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import csv
import os

from itemadapter import ItemAdapter


class FmPipeline:
    def process_item(self, item, spider):
        # 判断是否存在download文件夹，如果没有则创建
        download_path = os.getcwd() + '/download/'  # 当前文件夹下的download文件夹
        if not os.path.exists(download_path):  # 判断文件夹或文件
            os.makedirs(download_path)

        # 将图片保存
        img_name = item.get("img_name")
        img_byte = item.get("img_byte")
        if img_name:
            with open(download_path + img_name, "wb") as f:
                f.write(img_byte)
                print("保存图片%s完成....ok" % img_name)
            return

        title = item.get("title")
        # rank_number = item.get("rank_number")
        # img_url = item.get("img_url")
        # desc = item.get("desc")
        # play_number = item.get("play_number")
        if title:
            # 如果是信息，就保存到csv文件
            with open(download_path + '蜻蜓FM.csv', 'a') as f:
                # 创建一个csv的DictWriter对象，这样才能够将写入csv格式数据到这个文件
                f_csv = csv.DictWriter(f, ['title', 'rank_number', 'img_url', 'desc', 'play_number'])
                # 写入多行行（当做数据）
                f_csv.writerows([item])
                print("保存信息到CSV....ok")
